#! /usr/bin/env python
# -*- coding: utf-8 -*-

# Copyright (c) JoinQuant Development Team
# Author: Huayong Kuang <kuanghuayong@joinquant.com>

import cmd
import string, sys


class CLI(cmd.Cmd):

    def __init__(self):
        cmd.Cmd.__init__(self)
        self.prompt = '> '

        self.is_cmd = False

        self.do_q = self._quit = self.do_exit

    def precmd(self, line):
        print "precmd", line
        if line.startswith("@"):
            self.is_cmd = True
            return line[1:]
        return line

    def onecmd(self, line):
        if self.is_cmd:
            return getattr(self, "do_" + line)()

        print "--------", line

    def do_hello(self, arg):
        print "hello again", arg, "!"

    def help_hello(self):
        print "syntax: hello [message]",
        print "-- prints a hello message"

    def do_help(self):
        print "This is help"

    def do_quit(self, arg):
        sys.exit(1)

    def help_quit(self):
        print "syntax: quit",
        print "-- terminates the application"

    def do_exit(self, *args):
        return True

    def default(self, arg):
        print "-- ", arg
        return True

    def postloop(self):
        print("\nBye")

    # shortcuts
    do_q = do_quit

# try it out
cli = CLI()
cli.cmdloop()
